package com.tarena.lbs.business.servcie.impl;

import com.github.pagehelper.PageHelper;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.feign.AdminFeignClient;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreMapper storeMapper;
    private StoreRepository storeRepository;
    @Autowired
    private AdminFeignClient adminFeignClient;

    @Override
    public PageResult<StoreVO> getStoreByCity(AreaStoreQuery query) {
        log.debug("查询区域下的店铺列表");
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        log.debug("从query中获取PageNo页码","从query中提取PageSize每页数量");
        List<StoreVO> storeList = storeMapper.getStoreByCity(query);
        log.debug("查询区域下的店铺列表成功，出参:{}", storeList);
//            for (StoreVO storeVO : list){
//                List<PictureVO> pictureVOS = storeMapper.getStoreImages(storeVO.getId());
//                storeVO.setPictureVOS(pictureVOS);
//        }
        PageInfo<StoreVO> pageInfo = new PageInfo<>(storeList);
        log.debug("获取已经分页和分页数量的元数据: 当前页 {}, 总记录数 {}, 总页数 {}",
                pageInfo.getPageNum(), //补充获取当前页码
                pageInfo.getTotal(), //补充获取总记录数量
                pageInfo.getPages());//补充获取总分页数
        //页面大小（pageSize）：当前页最多显示的数据量
        //页码（pageNo）：当前请求的页数，请求的起始页

        //核心解耦工具
        PageResult<StoreVO> result = new PageResult<>();
        result.setObjects(storeList);       // 当前页业务数据（门店列表）
        result.setPageNo(pageInfo.getPageNum()); // 当前页码
        result.setPageSize(pageInfo.getPageSize()); // 每页条数
        result.setTotal(pageInfo.getTotal());     // 总记录数

        return result;
    }



    public void save(StoreParam param) {
        log.debug("保存店铺信息业务，入参:{}", param);
        StorePO po = new StorePO();
        BeanUtils.copyProperties(param, po);
        po.setCreateTime(new Date());
        List<String> storeImagesIds = param.getStoreImagesIds();
        po.setStoreImagesId(String.join(",", storeImagesIds));
        po.setStoreLatitude(param.getLatitude());
        po.setStoreLongitude(param.getLongitude());
        log.info("保存店铺信息业务，入参转换成PO:{}", po);
        storeRepository.save(po);


    }

    @Override
    public PageResult<StoreVO> pageList(StoreQuery query) throws BusinessException {
        log.debug("分页查询店铺列表业务，入参:{}", query);
        //解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.debug("userPrinciple:{}",userPrinciple);
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        log.debug("用户id：{}",userId);
        Integer businessId = adminFeignClient.selectBidById(userId).getData();
        query.setBusinessId(businessId);
        //创建一个新的分页结果对象
        PageResult<StoreVO> voPage = new PageResult<>(query);
        //total objects pageNo pageSize totalPage
        //调用 businessRepository 的 gePages 方法进行分页查询，获取包含商家持久化对象的分页信息
        PageInfo<StorePO> pageInfo = storeRepository.pagesList(query);
        //pageNo pageSize total
        // 将分页信息中的页码设置到分页结果对象中
        voPage.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        voPage.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        voPage.setTotal(pageInfo.getTotal());
        // 声明一个存储商家视图对象的列表
        List<StoreVO> vos = null;
        // 从分页信息中获取管理员持久化对象列表
        List<StorePO> pos = pageInfo.getList();
        // 判断持久化对象列表是否不为空
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    @Override
    public StoreVO getDetail(Integer id) {
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties( storeRepository.getDetail(id),storeVO);
        return storeVO;
    }

    @Override
    public int delete(Integer id) {

        return storeRepository.delete(id);
    }

    @Override
    public int updateStatus(Integer id) {
        return storeRepository.updateStatus(id);
    }



    public boolean isAllFieldsEmpty(StoreQuery query) {
        if (query == null) {
            return true;
        }

        // 检查所有字段是否为空或空字符串
        return (query.getBusinessId() == null) &&
                (query.getProvinceId() == null) &&
                (query.getAreaId() == null) &&
                (query.getCityId() == null) &&
                (query.getStoreStatus() == null) &&
                (query.getStartingTime() == null) &&
                (query.getEndTime() == null) &&
                !StringUtils.hasText(query.getStoreName()) &&
                !StringUtils.hasText(query.getStoreHeadPhone());
    }

}
